var imgs = [
  {
    src: "./images/div1/list-image/index1.png",
    href: "https://www.mi.com/shop/buy/detail?product_id=21432",
  },
  {
    src: "./images/div1/list-image/index2.png",
    href: "https://www.mi.com/shop/buy/detail?product_id=21423",
  },
  {
    src: "./images/div1/list-image/index3.png",
    href: "https://www.mi.com/shop/buy/detail?product_id=21406",
  },
  {
    src: "./images/div1/list-image/index4.png",
    href: "https://www.mi.com/shop/buy/detail?product_id=21404",
  },
  {
    src: "./images/div1/list-image/index5.png",
    href: "https://www.mi.com/shop/buy/detail?product_id=21413",
  },
  {
    src: "./images/div1/list-image/index6.png",
    href: "https://www.mi.com/shop/buy/detail?product_id=21271",
  },
];

var a = document.querySelector('.banner-cover');
var img = document.querySelector('.banner-cover img');
var pointerLeft = document.querySelector('.banner-pointer-left');
var pointerRight = document.querySelector('.banner-pointer-right');
var dots = document.querySelector('.banner-dots');
var index = 1;
var timer = null;
var curIndex = 0;

function init() {
  a.href = imgs[0].href;
  img.src = imgs[0].src;
  for (var i = 0; i < imgs.length; i++){
    var dot = document.createElement('span');
    dot.className = i===0?'banner-dots-selected fl':'fl';
    dots.appendChild(dot);
  }
}

function loopImages() {
  if (timer != null) {
    return;
  }
  timer = setInterval(next, 2000);
}

function stopLoop() {
  clearInterval(timer);
  timer = null;
}

function change(dotsIndex) {
  curIndex = dotsIndex;
  a.href = imgs[dotsIndex].href;
  img.src = imgs[dotsIndex].src;
  var selected = dots.querySelector(".banner-dots-selected");
  if (selected) {
    selected.className = 'fl';
  }
  dots.children[dotsIndex].className = "banner-dots-selected fl";
}

function prev() {
  curIndex--;
  if (curIndex < 0) {
    curIndex = imgs.length - 1;
  }
  index = curIndex+1;
  change(curIndex);
}

function next() {
  index = index % 6;
  change(index);
  index++;
}

img.addEventListener('mouseenter', stopLoop);
dots.addEventListener('mouseenter', stopLoop);
pointerLeft.addEventListener('mouseenter', stopLoop);
pointerRight.addEventListener('mouseenter', stopLoop);
img.addEventListener('mouseleave', loopImages);
dots.addEventListener("mouseleave", loopImages);
pointerLeft.addEventListener("mouseleave", loopImages);
pointerRight.addEventListener("mouseleave", loopImages);

dots.addEventListener('click', function (e) {
  var children = this.children;
  var childIndex = Array.prototype.slice.call(children).indexOf(e.target);
  change(childIndex);
  index = childIndex + 1;
});
pointerLeft.addEventListener('click', prev);
pointerRight.addEventListener('click', next);

init();
loopImages();